package com.ghd.dataviz.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ghd.dataviz.constant.UploadPath;
import com.ghd.dataviz.entity.FileUploadInfo;
import com.ghd.dataviz.mapper.FileUploadInfoMapper;
import com.ghd.dataviz.service.IFileUploadInfoService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author guohd
 * @since 2020-03-22
 */
@Slf4j
@Service
public class FileUploadInfoServiceImpl extends ServiceImpl<FileUploadInfoMapper, FileUploadInfo> implements IFileUploadInfoService {

    @Autowired
    private UploadPath uploadPath;

    @SneakyThrows
    @Override
    public Long insertPageInfo(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        log.debug(fileName + "-->" + size);

        long nanoTime = System.nanoTime();
        String path = uploadPath.getPath() + File.separator
                + nanoTime + File.separator + fileName;
        File dest = new File(path);
        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //保存文件
        } catch (Exception e) {
            log.error("错误", e);
            throw e;
        }
        FileUploadInfo uploadInfo = new FileUploadInfo();
        uploadInfo.setName(fileName);
        uploadInfo.setType(file.getContentType());
        uploadInfo.setPath(path);
        String url = nanoTime + "/" + fileName;
        uploadInfo.setUrl(url);
        uploadInfo.setStatus(1);
        this.save(uploadInfo);
        return uploadInfo.getId();
    }
}
